<?php
namespace Home\Controller;
use Think\Log;

/**
 * 我的订单
 * User: linkwhy
 * Date: 2015/10/27
 * Time: 14:27
 */
class OrderController extends HomeController{

    private $wechar_id = 0;
    private $mode = '';
    private $item = '';
	const SSECRET="aaa123456";

    public function _initialize(){
        $config = api('Config/lists');
        C($config); //添加配置
        $this->wechar_id = $_SESSION['wechat_id'];
        $this->mode = M('order');
        $this->item = M('order_item');
        define('DOWNTIME', 1800);
    }

    public function index(){
        autoVerifyReturnOrder($this->wechar_id);
        //判断该用户是否有未有确认收货的状态
        $take_count = $this->mode->where(array('client_id' => $this->wechar_id, 'order_status' => 3))->count();
        if( $take_count > 0 ){
            //有确认收货的状态，那么自动判断该用户是否在规定的收货期限内确认收货
            $this->auto_sureGoods();
        }
        $type = I('get.type');
        $fields = 'o.id,o.order_id,order_status,pock_money,take_time,rg.return_status,shop_id,is_clear,ctime,rg.order_id as return_order_id,o.wl_order,o.wl_name';
        $where = array();
        $rgoods = M('return_goods');
        $ritem = M('return_item');
        switch($type){
            case 0:
                //全部
                $where = array('o.client_id' => $this->wechar_id);
                $data['name'] = '全部订单';
                break;
            case 1:
                //待付款
                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 0);
                $data['name'] = '待付款';
                break;
            case 2:
                //待发货
                //$where = array('o.client_id' => $this->wechar_id, 'order_status' => 2);
                $where = "o.client_id = {$this->wechar_id} and order_status in(2,3)";
                $data['name'] = '待发货';
                break;
            case 3:
                //待收货
//                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 3);
                $where = "o.client_id = {$this->wechar_id} and order_status in(2,3)";
                $data['name'] = '待收货';
                break;
            case 4:
                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 4);
                break;
        }

        $list = $this->mode->alias('o')->field($fields)->join('__RETURN_GOODS__ rg ON rg.order = o.order_id', 'LEFT')->where($where)->order('id desc')->select();

        foreach($list as $key => &$val){
            $list[$key]['item'] = $this->item->alias('item')->field('item.order_id,c.goods_id,c.id as cart_id,g.name,g.picture,g.price,g.zhekou,c.num,c.color,c.size,shop_price,foot_width,foot_long,foot_thick')
                ->join('__CART__ c ON item.cart_id = c.id')
                ->join('__GOODS__ g ON c.goods_id = g.id')
                ->where(array('c.is_create' => 1, 'order_id' => $val['order_id']))->select();
			if($val['is_clear'] == 0){
				$val['is_take'] = 0;
				if( intval($val['order_status']) == 4 && empty($val['return_status']) ){    //交易成功和未退货
					$val['is_take'] = $this->is_user_have_return($val['take_time'], $val['is_clear'], $val['shop_id'], $val['order_id']);
				}
			}else{
				$val['is_take'] = 1;
			}

            if( $val['order_status'] == 0 ){
                $count_down_time = ((int)$val['ctime'] + DOWNTIME) - time();
                if( $count_down_time > 0  ){
                    $val['end_time'] = $count_down_time;
                }else{
                    //时间过了关闭该订单
                    M('order')->where(array('id' => $val['id']))->setField('order_status', 5);
                    $val['end_time'] = 0;
                }
            }
        }


        foreach($list as $k => &$v){
            foreach($v['item'] as $k1 => &$v2){
                $row = $rgoods->alias('rg')->join('__RETURN_ITEM__ i ON i.order_id = rg.order_id')->where(array('order' => $v2['order_id'], 'goods_id' => $v2['goods_id'], 'cart_id' => $v2['cart_id']))->find();
                if($row){
                    $v2['return_status'] = $row['return_status'];
                }else{
                    $v2['return_status'] = 1;
                }
                $v2['priceAll'] = floatval($v2['price']) * intval($v2['num']);
                $v['count'] += $v2['num'];
                $v['zhekouAll'] += (floatval($v2['price']) * intval($v2['num'])) * (intval($v2['zhekou'])/100);
                unset($row);
            }
            $v['return_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 2))->count();
            $v['return_success_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 3))->count();
            $v['return_cancel_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 4))->count();
            //$v['return_all_count'] = $rgoods->where(array('order' => $v['order_id'], 'return_status' =>))
        }
        $data['shop_id'] = $_SESSION['shopid'];
        $data['user_id'] = $_SESSION['userid'];
        $this->assign('data', $data);
        $this->assign('list', $list);
        $this->assign('type', $type);
        $this->display();
    }

    /**
     * 订单详情
     */
    public function order_detail(){
        $order_id = I('get.order_id');
        $cd = M('clients_address','caitou_','DB_CONFIG1');
        $row = $this->mode->alias('o')->field('o.id,o.order_id,order_status,pock_money,take_time,rg.return_status,shop_id,is_clear,ctime,take_id,rg.order_id as return_order_id,o.wl_order,o.wl_name')
                ->join('__RETURN_GOODS__ rg ON rg.order = o.order_id', 'LEFT')
                ->where(array('o.order_id' => $order_id))->find();

        //查看订单是否到期
        if( (int)$row['order_status'] == 0 ){
            $count_down_time = ((int)$row['ctime'] + DOWNTIME) - time();
            if( $count_down_time <= 0  ){
                M('order')->where(array('id' => $row['id']))->setField('order_status', 5);
            }
        }

        $row2 = $cd->field('pro_id,city_id,area_id,name,phone,address')->where(array('id' => $row['take_id']))->find();
        $list = $this->item->alias('item')->field('item.order_id,c.goods_id,c.id as cart_id,g.name,g.picture,g.price,g.zhekou,c.num,c.color,c.size,shop_price,foot_width,foot_long,foot_thick')
            ->join('__CART__ c ON item.cart_id = c.id')
            ->join('__GOODS__ g ON c.goods_id = g.id')
            ->where(array('c.is_create' => 1, 'order_id' => $row['order_id']))->select();
        if($row['is_clear'] == 0){
            $row['is_take'] = 0;
            if( intval($row['order_status']) == 4 && empty($row['return_status']) ){    //交易成功和未退货
                $row['is_take'] = $this->is_user_have_return($row['take_time'], $row['is_clear'], $row['shop_id'], $row['order_id']);
            }
        }else{
            $row['is_take'] = 1;
        }
        $data['name'] = '订单详情';
        if( $row2 ){
			$new_row = array_merge($row, $row2);
		}else{
			$new_row = $row;
		}

        $this->assign('row', $new_row);
        $this->assign('list', $list);
        $this->assign('data', $data);
        $this->display();
    }


    public function return_index(){
        $rgoods = M('return_goods');
    }

    /**
     * 取消订单
     */
    public function cancel_order(){
        $data['order_status'] = 5;
        $data['msg'] = I('get.return_msg');
        if($this->mode->where(array('order_id' => I('get.order_id')))->save($data)){
            $this->ajaxReturn(array('status' => true));
        }else{
            $this->ajaxReturn(array('status' => false));
        }
    }

    public function order_index(){
        $cart_id = I('post.id');
        if( empty($cart_id) ){
            $cart_id = $_SESSION['cartid'];
        }else{
            $_SESSION['cartid'] = $cart_id;
        }
        $cart = M('cart');
        $data = M('clients_address','caitou_','DB_CONFIG1')->field('id,pro_id,city_id,area_id,name as sname,phone,address,code,default')->where(array('cid' => $this->wechar_id, 'default' => 1, 'is_del' => 0))->find();   //收货地址
        $data['pro_name'] = $this->getAreaName($data['pro_id']);
        $data['city_name'] = $this->getAreaName($data['city_id']);
        $data['area_name'] = $this->getAreaName($data['area_id']);

        $list = array();
        $priceAll = 0;
        $goods_num = 0;

        $row = $cart->alias('c')->field('g.id,g.name,g.picture,g.price,g.zhekou,c.id as cart_id,c.num,c.color,c.size,shop_price,foot_width,foot_long,foot_thick,is_patch')
            ->join('__GOODS__ g ON c.goods_id = g.id', 'left')->join('__GOODS_CLASS__ gc ON g.class_id = gc.id', 'left')->where(array('c.id' => $cart_id, 'client_id' => $this->wechar_id, 'is_create' => 0))->find();

        $priceAll += floatval($row['price']) * intval($row['num']);
        $goods_num += intval($row['num']);

        $data['name'] = '订单确认';
        if( (int)$row['is_patch'] == 1 ){
            if($priceAll < 100){
                $data['priceAll'] = $priceAll + (int)C('FARE');
                $data['fare'] = C('FARE');
            }else{
                $data['priceAll'] = $priceAll;
            }
        }else{
            $data['priceAll'] = $priceAll;
        }
        $data['pricenum'] = $priceAll;
        $data['goods_num'] = $goods_num;
        $this->assign('row', $row);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 生成订单
     */
    public function create_order(){
        $cart_ids = I('post.cart_id', '');
        if($cart_ids != ''){
            $cdh = build_order_no($this->wechar_id);
            $row = M('clients_address','caitou_','DB_CONFIG1')->field(true)->where(array('id' => I('post.take_id')))->find();
            $take_text = "收货人：{$row['name']}&nbsp;联系电话：{$row['phone']}&nbsp;联系地址：" . getAreaName($row['pro_id']) . getAreaName($row['city_id']) . getAreaName($row['area_id']) . $row['address'] . "&nbsp;邮编：{$row['code']}";
            $data = array(
                'client_id' => $this->wechar_id,
                'order_id' => $cdh,
                'xf_money' => 0,
                'pock_money' => I('post.pock_money'),
                'order_status' => 0,
                'take_status' => 0,
                'return_status' => 0,
                'is_read' => 0,
                'ctime' => time(),
                'pay_time' => 0,
                'msg' => I('post.msg', ''),
                'take_id' => I('post.take_id'),
                'shop_id' => $_SESSION['shopid'],
                'take_text' => $take_text
            );
            $this->mode->create($data);
            $cart = M('cart');
            $goods = M('goods');
            if($this->mode->add()){
                $zhekou = 0;
                $add_data = array('cart_id' => $cart_ids, 'order_id' => $cdh);
//                foreach($cart_ids as $key => $val){
//
                    if($cart->where(array('id' => $cart_ids))->setField('is_create', 1)){
                        $row_temp = $cart->alias('c')->field('num,price,zhekou')->join('__GOODS__ g ON c.goods_id = g.id')->where(array('c.id' => $cart_ids, 'client_id' => $this->wechar_id))->find();
                        $zhekou += (floatval($row_temp['price']) * intval($row_temp['num'])) * (intval($row_temp['zhekou'])/100);
                    }
//                }
                if(M('order_item')->add($add_data)){
                    $_SESSION['data'] = array('pock_money' => I('post.pock_money'), 'order_id' => $cdh, 'zhekouAll' => $zhekou);
                    $this->ajaxReturn(array('status' => true, 'url' => U('order_success')));
                }else{
                    $this->ajaxReturn(array('status' => false, 'info' => '订单生成失败！'));
                }
            }
        }else{
            $this->ajaxReturn(array('status' => false, 'info' => '参数错误'));
        }
    }

    public function againNewOrder(){
        $order_id = I('get.order_id');
        $cdh = build_order_no($this->wechar_id);
        if( $this->mode->where(array('order_id' => $order_id))->setField('order_id', $cdh) ){
            if( $this->item->where(array('order_id' => $order_id))->setField('order_id', $cdh) ){
                $_SESSION['data']['order_id'] = $cdh;
                $this->ajaxReturn(array('status' => true, 'order_id' => $cdh));
            }else{
                $this->ajaxReturn(array('status1' => false));
            }
        }else{
            $this->ajaxReturn(array('status2' => false));
        }
    }

    /**
     * 订单生成成功
     */
    public function order_success(){
        $data = M('clients_address','caitou_','DB_CONFIG1')->field('id,pro_id,city_id,area_id,name as sname,phone,address,code,default')->where(array(cid => $this->wechar_id, 'default' => 1))->find();   //收货地址
        $data['pro_name'] = $this->getAreaName($data['pro_id']);
        $data['city_name'] = $this->getAreaName($data['city_id']);
        $data['area_name'] = $this->getAreaName($data['area_id']);
        $data['pock_money'] = $_SESSION['data']['pock_money'];
        $data['order_id'] = $_SESSION['data']['order_id'];
        $data['zhekouAll'] = $_SESSION['data']['zhekouAll'];
        $_SESSION['order_id'] = $_SESSION['data']['order_id'];
        $data['shop_id'] = $_SESSION['shopid'];
        $data['user_id'] = $_SESSION['userid'];
        $data['name'] = '立即支付';
        $this->assign('data', $data);
        $this->display();
    }

    public function getAreaName($area_id){
        $area = M('areas');
        $row = $area->field('area_name')->where(array('area_id' => $area_id))->find();
        return $row['area_name'];
    }

    /**
     * 查看物流
     */
    public function querywuliu(){
        //物流借口
        $exp = A('Express');
        $data = $this->mode->field('wl_order,wl_name')->where(array('order_id' => I('get.order_id')))->find();
        $data['name'] = '物流信息';
        $result  = $exp -> getorder( $data['wl_order']);
        $this->assign('list', $result['data']);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 确认收货
     */
    public function sureGoods(){
        $type = I('post.type', 0);
        $order_id = I('post.order_id');
        if($this->mode->where(array('order_id' => $order_id))->save(array('order_status' => 4, 'take_time' => time(), 'take_status' => 2))){
            $this->ajaxReturn(array('status' => true, 'info' => '交易成功！'));
        }else{
            $this->ajaxReturn(array('status' => false, 'info' => '交易失败！'));
        }
    }

    /**
     * 自动判断用户收货时间
     */
    public function auto_sureGoods(){
        //读取收获期限天数
        $take_time = C('TAKETIME');
        $order = M('order');
        //获取卖家发货时间
        $list_time = $order->field('id,order_id,send_time')->where(array('client_id' => $this->wechar_id, 'order_status' => 3))->select();
        //计算收货期限的时间戳
        $temp_time = 60*60*24 * intval($take_time);
        $current_time = time();
        $end_time = 0;
        foreach($list_time as $key => $val){
            $end_time = $temp_time + intval($val['send_time']);
            if( $current_time > $end_time ){
                //更改订单状态为交易成功
                $order->where( array( 'id' => $val['id'], 'order_id' => $val['order_id'] ) )->save(array('order_status' => 4, 'take_time' => $current_time, 'take_status' => 2));
            }
        }
    }

    /**
     * 判断用户确认收货后在规定的退货时间内是否拥有退货功能
     */
    public function is_user_have_return($take_time, $is_claer, $shop_id, $order_id){
			//读取退货期限天数
			$return_time = C('RETURNTIME');
			//获取买家确认收货时间
			//计算退货期限的时间戳
			$end_time = 60*60*24 * intval( $return_time ) + intval($take_time);
			$current_time = time();
			if($current_time > $end_time){
				//过了退货时间
				if($is_claer == 0){
					//可以实现放款的操作
					$rs = $this->makeMoney($order_id, $shop_id);
					if($rs == 1){
						//清算操作
						$this->mode->where(array('order_id' => $order_id))->save(array('is_clear' => 1, 'order_status' => 6, 'success_time' => time()));
					}
				}
                return 1;
			}else{
				//未过退货时间
				return 0;
			}
    }
	//确认不退货
	public function sureNotGoods(){
		//可以实现放款的操作
		$order_id = I('get.order_id');
		$shop_id = $_SESSION['shopid'];
		$rs = $this->makeMoney($order_id, $shop_id);
		if($rs == 1){
			//清算操作
            //修改商品销售数量
            $this->updateSaleCount($order_id);
			if($this->mode->where(array('order_id' => $order_id))->save(array('is_clear' => 1, 'order_status' => 6, 'success_time' => time()))){
				$this->ajaxReturn(array('status' => true, 'info' => '确认不退货成功！'));
			}
		}else{
			$this->ajaxReturn(array('status' => false, 'info' => '确认不退货失败！'));
		}
	}

    /**
     * 修改销量
     */
	public function updateSaleCount($order_id){
        $item = M('order_item');
        $goods = M('goods');
        $list = $item->alias('item')->field('goods_id,num')->join('__CART__ c ON item.cart_id = c.id')->where(array('order_id' => $order_id))->select();
        foreach($list as $val){
            $goods->where(array('id' => $val['goods_id']))->setInc('sale_count', intval($val['num']));
        }
    }
	
	/**
     * 放款 确认订单完成操作
     */
    public function makeMoney($order_id, $seller_id){
		
        //参数　order_id：商城提交时的订单id
        //      seller_id:商城点商店铺id
        $arr=array('order_id'=>"$order_id","seller_id"=>"$seller_id");

        ksort($arr);
        $str="";
        foreach($arr as $k=>$v){

            $str.=$k.$v;

        }
        //echo $str;
        $sign=md5($str."aaa123456");
        $arr['sign']=$sign;

        //echo $str."aaa123456";
        //http://120.25.151.137 测试服
        //182.92.31.222/ 正式服
        //返回1代表成功　０代表失败
        return $this->apiPost("http://182.92.31.222/server/index.php?c=Order&a=completeOrderEShop",$arr);
    }
	
	
	/**
	 * 异步提交
	 * @param $uri
	 * @param $post_data
	 * @return bool
	 */
	public function apiPost($uri,$post_data){
		//$post_data = array ("username" => "bob","key" => "12345");
		$ch = curl_init();
		$headr[] ="X-Requested-With:1";
		$headr[] ="UID:0";
		$headr[] ="SESSION:0";
		//$header[]= "Content-Type: application/x-www-form-urlencoded";
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
		$output = curl_exec($ch);
		$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		if($output!="1"){
			echo $output;
			//var_dump($post_data);
			return false;
		}
		//打印获得的数据
		return true;
	}

}

